'use strict';
const D3Node = require('d3-node')

const dbHelper = require("db-helper")
const uniID = require("uni-id")
const fs = require("fs")
const path = require("path")
const images = require("images")
const {CLOUDURL} = require('config')

const imgPrefixBase64 = 'data:image/png;base64,'
const downloadImg = async (url, filePath) => {
	return new Promise(async (resolve, reject) => {
		try {
			// console.log("下载", url);
			let res = await uniCloud.httpclient.request(url);
			resolve(res.data);
		} catch (e) {
			reject(e);
		}
	})
}
exports.main = async (event, context) => {
	console.log('达人海报');
	//event为客户端上传的参数
	let {
		posterId,
		token,
		queryStringParameters
	} = event;
	if (!posterId && queryStringParameters) {
		posterId = queryStringParameters.posterId;
	}
	if (!token && queryStringParameters) {
		token = queryStringParameters.token;
	}
	if (!token) {
		return {
			code: 401,
			msg: 'token失效，请重新登陆'
		}
	}
	if (!posterId) {
		return {
			code: 500,
			msg: "参数错误"
		}
	}
	let qrcodePath, posterPath, combinedPath;
	try {
		const payload = await uniID.checkToken(token)
		if (payload.code) { // code不为0代表token校验未通过
			return {
				code: 401,
				msg: 'token失效，请重新登陆'
			}
		}
		let poster = await dbHelper.getById("t3ds-share-expert-poster", posterId);
		if (!poster) {
			return {
				code: 500,
				msg: "海报不存在"
			}
		}
		const codeRes = await uniCloud.callFunction({
			name: "uni-admin",
			data: {
				action: 'member-self/getMyShareCode',
				uniIdToken: token
			}
		})
		if (codeRes.result.code !== 200) {
			return {
				code: 500,
				msg: codeRes.result.msg || codeRes.result.message
			}
		}
		let fileName = `poster_${payload.userInfo._id}_${posterId}.jpg`
		let cache = await dbHelper.getOne("file-cache", {
			srcUrl: fileName
		})
		if (cache) {
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': cache.cachedUrl
				}
			}
		}
		let text = encodeURIComponent(`https://test.the3dspace.cn/register-share-expert?codeId=${codeRes.result.result._id}@`);
		let qrcodeBuff = await downloadImg(`${CLOUDURL}/genQRCode?text=${text}`);
		let qrcodeImgSize = 276;
		let qrcodeImg = images(qrcodeBuff).resize(438, 438);
		let posterBuff = await downloadImg(poster.url);
		let posterImg = images(posterBuff).resize(1080, 1620);
		let qrcodeImgX = 321
		let qrcodeImgY = 608

		let combined = posterImg.draw(qrcodeImg, qrcodeImgX, qrcodeImgY).encode("jpg", {
			operation: 50
		});

		let res = await uniCloud.uploadFile({
			cloudPath: "fileCache/" + fileName,
			fileContent: combined
		})
		console.log('updated', res)
		let {fileID} = res
		if (uniCloud.$provider == 'aliyun') {
			await dbHelper.insert("file-cache", {
				srcUrl: fileName,
				cachedUrl: fileID,
				fileID: fileID
			})
			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': fileID
				}
			}
		} else {
			res = await uniCloud.getTempFileURL({
				fileList: [fileID]
			})
			let {fileList} = res
			await dbHelper.insert("file-cache", {
				srcUrl: fileName,
				cachedUrl: fileList[0].download_url,
				fileID: fileID
			})

			return {
				mpserverlessComposedResponse: true, // 使用阿里云返回集成响应是需要此字段为true
				isBase64Encoded: false,
				statusCode: 301,
				headers: {
					'location': fileList[0].download_url
				}
			}
		}
	} catch (e) {
		console.error("获取我的海报遇到错误", e);
		return {
			code: 500,
			msg: e.message
		}
	}
};